package cn.innosmart.aq.view.activity;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.SensorEvent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sensor.UMSensor;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

import cn.innosmart.aq.R;
import cn.innosmart.aq.customize.photosharelibrary.bean.ImageFloder;
import cn.innosmart.aq.customize.photosharelibrary.imageloader.ListImageDirPopupWindow;
import cn.innosmart.aq.customize.photosharelibrary.imageloader.MyAdapter;
import cn.innosmart.aq.util.ImageComTools;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/8/31.
 */
public class ImageSelectActivity extends BaseActivity implements ListImageDirPopupWindow.OnImageDirSelected {
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static String LOG_TAG = "ImageSelectActivity";
    private final int EXIT = 0;
    int totalCount = 0;
    SocializeListeners.SnsPostListener snsPostListener = new UMSensor.OnSensorListener() {
        @Override
        public void onActionComplete(SensorEvent sensorEvent) {
        }

        @Override
        public void onButtonClick(UMSensor.WhitchButton whitchButton) {
        }

        @Override
        public void onStart() {
            exit();
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
            if (i == 200) {
                showToast(getString(R.string.activity_imageselect_share_success));
            } else if (i == 40000) {
                showToast(getString(R.string.activity_imageselect_cancel_share));
            } else {
                showToast(getString(R.string.activity_imageselect_share_failed));
            }
        }
    };
    private ProgressDialog mProgressDialog;
    /**
     * 存储文件夹中的图片数量
     */
    private int mPicsSize;
    /**
     * 图片数量最多的文件夹
     */
    private File mImgDir;
    /**
     * 所有的图片
     */
    private List<String> mImgs;
    private GridView mGirdView;
    private MyAdapter mAdapter;
    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();
    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
    private RelativeLayout mBottomLy;

    ;
    private TextView mChooseDir;
    private TextView mImageCount;
    private int mScreenHeight;
    private ListImageDirPopupWindow mListImageDirPopupWindow;
    private ArrayList<File> allFileList = new ArrayList<File>();
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private UMSocialService mController;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            switch (menuItem.getItemId()) {
                case R.id.action_next:

                    if (MyAdapter.mSelectedImage.size() == 1) {
                        int flag = getIntent().getIntExtra("flag", 0);
                        if (flag == 2) {
                            String url = MyAdapter.mSelectedImage.get(0);
                            Intent intent = getIntent();
                            intent.putExtra("imageurl", url);
                            setResult(1002, intent);
                            finish();
                        } else {
                            WeiXinShareContent weixinContent = new WeiXinShareContent();
                            CircleShareContent circleMedia = new CircleShareContent();
                            mController.setShareMedia(circleMedia);
                            Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ictest);
                            Bitmap rawBitmap1 = ImageComTools.scaleBitmap(MyAdapter.mSelectedImage.get(0), 640);
                            Bitmap bitmap = ImageComTools.watermarkBitmap(rawBitmap1, rawBitmap, null);
                            //微信好友设置
                            weixinContent.setShareImage(new UMImage(ImageSelectActivity.this, bitmap));
                            weixinContent.setTitle("友盟社会化分享组件-微信");
                            weixinContent.setTargetUrl("你的URL链接");
                            mController.setShareMedia(weixinContent);
                            //微信朋友圈设置
                            circleMedia.setShareImage(new UMImage(ImageSelectActivity.this, bitmap));
                            circleMedia.setTargetUrl("你的URL链接");
                            mController.setShareMedia(circleMedia);
                            //设置微信的回调
                            mController.getConfig().registerListener(snsPostListener);
                            //分享
                            mController.openShare(ImageSelectActivity.this, false);
                        }

                    } else {
                        showToast(getString(R.string.activity_imageselect_select_picture));
                    }
                    break;

            }
            return true;
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
                case 0x110:
                    mProgressDialog.dismiss();
                    // 为View绑定数据
                    data2View();
                    // 初始化展示文件夹的popupWindw
                    initListDirPopupWindw();
                    break;
            }
        }
    };
    private ImageFloder allFloader = null;
    private Uri fileUri;
    private View.OnClickListener cameraOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("Open the Camera!");
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // create a file to save the image
//            fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
            // create a file to save the image
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

            // 此处这句intent的值设置关系到后面的onActivityResult中会进入那个分支，即关系到data是否为null，如果此处指定，则后来的data为null
            // set the image file name
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            // 此处这句intent的值设置关系到后面的onActivityResult中会进入那个分支，即关系到data是否为null，如果此处指定，则后来的data为null
            // set the image file name
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    };

    /**
     * Create a file Uri for saving an image or video
     */
    private static Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * Create a File for saving an image or video
     */
    private static File getOutputMediaFile(int type) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = null;
        try {
            // This location works best if you want the created images to be
            // shared
            // between applications and persist after your app has been
            // uninstalled.
            mediaStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "MyCameraApp");

            Log.d("ImageSelectActivity", "Successfully created mediaStorageDir: "
                    + mediaStorageDir);

        } catch (Exception e) {
            e.printStackTrace();
            Log.d(LOG_TAG, "Error in Creating mediaStorageDir: "
                    + mediaStorageDir);
        }

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                // 在SD卡上创建文件夹需要权限：
                // <uses-permission
                // android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                Log.d(LOG_TAG,
                        "failed to create directory, check if you have the WRITE_EXTERNAL_STORAGE permission");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    /**
     * 为View绑定数据
     */
    private void data2View() {
        if (mImgDir == null) {
            Toast.makeText(getApplicationContext(), R.string.activity_imageselect_search_no_pic, Toast.LENGTH_SHORT).show();
            return;
        }

        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        Collections.sort(allFileList, new FileComparator());
        mImgs = new ArrayList<>();
        for (int i = 0; i < allFileList.size(); i++) {
            mImgs.add(allFileList.get(i).getPath());
        }
        mAdapter = new MyAdapter(getApplicationContext(), mImgs,
                R.layout.grid_item, mImgDir.getAbsolutePath());
//        mAdapter.setOnclickListener(cameraOnClickListener);
        mGirdView.setAdapter(mAdapter);
        mImageCount.setText(totalCount + getString(R.string.activity_imageselect_pic_unity));
    }

    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    /**
     * 初始化展示文件夹的popupWindw
     */
    private void initListDirPopupWindw() {
        mListImageDirPopupWindow = new ListImageDirPopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
                mImageFloders, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.list_dir, null));

        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        // 设置选择文件夹的回调
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_select);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenHeight = outMetrics.heightPixels;
        MyAdapter.mSelectedImage = new LinkedList<String>();
        setBar();
        initView();
        getImages();
        initEvent();
        intShare();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        getMenuInflater().inflate(R.menu.menu_image_select, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_imageselect_select_pic));
        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void intShare() {
        // 首先在您的Activity中添加如下成员变量
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
        // 设置分享内容
        mController.setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能，http://www.umeng.com/social");
        // 设置分享图片, 参数2为图片的url地址
//        mController.setShareMedia(new UMImage(ImageSelectActivity.this,
//                "http://www.umeng.com/images/pic/banner_module_social.png"));
        mController.getConfig().removePlatform(SHARE_MEDIA.RENREN,
                SHARE_MEDIA.DOUBAN, SHARE_MEDIA.SMS,
                SHARE_MEDIA.EMAIL, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA, SHARE_MEDIA.TENCENT
        );

    }

    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, R.string.activity_imageselect_no_storage, Toast.LENGTH_SHORT).show();
            return;
        }
        allFileList.clear();
        mImageFloders.clear();
        allFloader = new ImageFloder();
        allFloader.setDir(getString(R.string.activity_imageselect_dir_allfiles));
        mImageFloders.add(allFloader);
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, null, getString(R.string.activity_imageselect_loading));
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = ImageSelectActivity.this.getContentResolver();
                if (mDirPaths == null) {
                    mDirPaths = new HashSet<String>();
                }
                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);

                Log.e("TAG", mCursor.getCount() + "");
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    Log.e("TAG", path);
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;
                    //
                    File imageFile = new File(path);
                    allFileList.add(imageFile);
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new ImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                        allFloader.setFirstImagePath(path);
                    }
                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg")
                                    || filename.endsWith(".png")
                                    || filename.endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    }).length;
                    totalCount += picSize;
                    imageFloder.setCount(picSize);
                    allFloader.setCount(totalCount);
                    mImageFloders.add(imageFloder);

                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();

                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;

                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);

            }
        }).start();

    }

    /**
     * 初始化View
     */
    private void initView() {
        mGirdView = (GridView) findViewById(R.id.id_gridView);
        mChooseDir = (TextView) findViewById(R.id.id_choose_dir);
        mImageCount = (TextView) findViewById(R.id.id_total_count);

        mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);

    }

    private void initEvent() {
        /**
         * 为底部的布局设置点击事件，弹出popupWindow
         */
        mBottomLy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListImageDirPopupWindow
                        .setAnimationStyle(R.style.anim_popup_dir);
                mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);

                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = .3f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    public void selected(ImageFloder floder) {
        File[] imgs = new File[0];
        if (floder.getName().equals(getString(R.string.activity_imageselect_dir_allfiles))) {
            floder.setCount(totalCount);
            Collections.sort(allFileList, new FileComparator());
            mImgs = new ArrayList<>();
            mImgs.add("all");
            for (int i = 0; i < allFileList.size(); i++) {
                mImgs.add(allFileList.get(i).getPath());
            }
        } else {
            mImgDir = new File(floder.getDir());
            imgs = mImgDir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg"))
                        return true;
                    return false;
                }
            });
            Arrays.sort(imgs, new FileComparator());
            mImgs = new ArrayList<>();
            for (int i = 0; i < imgs.length; i++) {
                mImgs.add(imgs[i].getName());
            }
        }
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        mAdapter = new MyAdapter(getApplicationContext(), mImgs, R.layout.grid_item, mImgDir.getAbsolutePath());
//        mAdapter.setOnclickListener(cameraOnClickListener);
        mGirdView.setAdapter(mAdapter);
        mImageCount.setText(floder.getCount() + getString(R.string.activity_imageselect_pic_unity));
        mChooseDir.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE == requestCode) {
            getImages();
        }
    }

    private class FileComparator implements Comparator<File> {

        @Override
        public int compare(File lhs, File rhs) {
            if (lhs.lastModified() < rhs.lastModified()) {
                return 1;//最后修改的照片在前
            } else {
                return -1;
            }
        }

    }
}
